/*
 * IndexedDictionaryAdapter.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.dictionary;

import java.text.MessageFormat;

import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import de.studiorutton.colorschemes.IColorSchemeMapper;
import de.studiorutton.gerengdic.Prefs;
import de.studiorutton.gerengdic.R;
import de.studiorutton.gerengdic.databaseaccess.ContentAccess;
import de.studiorutton.gerengdic.dictionary.records.LeftRightValuesRecord;
import de.studiorutton.gerengdic.dictionary.records.IRecord;
import edu.sdsu.util.SortedList;

public class DictionaryAdapter extends BaseAdapter {
	private final static String TAG = "learningwords";

	private boolean isLoadingData;
	private RelativeLayout progressLayout;
	private SortedList<DictionaryRecord> data;
	private IDictionaryView dv;
	private Dictionary d;
	private int lastMaxError;

	private final static int VIEW_TYPE_COUNT = 3;

	// public DictionaryAdapter(IDictionaryView dv, Dictionary d,
	// Comparer<LeftRightValuesRecord> comp, int progressDrawableResourceId) {
	// this(dv, d, comp, progressDrawableResourceId);
	// }

	// public DictionaryAdapter(ExpandableListActivity activity,
	// int progressDrawableResourceId, Comparer<LeftRightValuesRecord> comp) {
	// this(activity, activity.getExpandableListView(),
	// progressDrawableResourceId, comp);
	// }

	public DictionaryAdapter(IDictionaryView dv, Dictionary d) {
		this.d = d;
		this.dv = dv;
		data = new SortedList<DictionaryRecord>(DictionaryRecord.dComparer);

		progressLayout = (RelativeLayout) LayoutInflater.from(dv.getContext())
				.inflate(R.layout.dictionaryprogress, null, false);
	}

	public void setDictionaryView(IDictionaryView dv) {
		this.dv = dv;
	}

	public RelativeLayout getProgressView() {
		return progressLayout;
	}

	/**
	 * {@inheritDoc}
	 * <p>
	 * Don't use this to check for the presence of actual data items; use
	 * {@link #hasItems()} instead.
	 * </p>
	 */
	public int getCount() {
		int size = 0;
		if (data != null) {
			size += data.size();
		}
		if (isLoadingData) {
			size += 1;
		}
		return size;
	}

	/**
	 * {@inheritDoc}
	 * <p>
	 * Don't use this to check for the presence of actual data items; use
	 * {@link #hasItems()} instead.
	 * </p>
	 */
	@Override
	public boolean isEmpty() {
		return getCount() == 0 && !isLoadingData;
	}

	/**
	 * @return the actual number of data items in this adapter, ignoring the
	 *         progress item.
	 */
	public int getItemCount() {
		if (data != null) {
			return data.size();
		}
		return 0;
	}

	/**
	 * @return true if there are actual data items, ignoring the progress item.
	 */
	public boolean hasItems() {
		return data != null && !data.isEmpty();
	}

	public DictionaryRecord getItem(int position) {
		if (data == null) {
			return null;
		}
		return data.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	@Override
	public boolean isEnabled(int position) {
		if (isPositionOfProgressElement(position)) {
			return false;
		}
		return true;
	}

	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

	public void setIsLoadingData(boolean isLoadingData) {
		setIsLoadingData(isLoadingData, true);
	}

	public void setIsLoadingData(boolean isLoadingData, boolean redrawList) {
		this.isLoadingData = isLoadingData;
		if (redrawList) {
			notifyDataSetChanged();
		}
	}

	public boolean isLoadingData() {
		return isLoadingData;
	}

	@Override
	public int getItemViewType(int position) {
		if (isLoadingData() && position == data.size())
			return 0;
		return data.get(position).type;
	}

	@Override
	public int getViewTypeCount() {
		return VIEW_TYPE_COUNT;
	}

	public final View getView(int position, View convertView, ViewGroup parent) {
		if (isPositionOfProgressElement(position)) {
			return progressLayout;
		}

		if (convertView == progressLayout) {
			// make sure the progress view is never used as a convert view
			convertView = null;
		}

		// Log.d(TAG, "IndexedDictionaryAdapter: -- starting -- ");
		// Log.d(TAG, "IndexedDictionaryAdapter: position = " + position + ".");

		DictionaryRecord dr = getItem(position);
		LinearLayout ll = null;
		if (dr.type == DictionaryRecord.TYPE_HEADLINE) {
			if (convertView == null) {
				ll = (LinearLayout) LayoutInflater
						.from(dv.getContext())
						.inflate(R.layout.dictionaryitemheadline, parent, false);
			} else
				ll = (LinearLayout) convertView;
			LinearLayout lld = (LinearLayout) ll
					.findViewById(R.id.searchheadline);
			createHeadline(position, lld);
		} else {
			if (convertView == null) {
				ll = (LinearLayout) LayoutInflater.from(dv.getContext())
						.inflate(R.layout.dictionaryitem, parent, false);
			} else
				ll = (LinearLayout) convertView;
			LinearLayout lld = (LinearLayout) ll.findViewById(R.id.searchitem);
			createContent(position, lld);
		}

		return ll;
	}

	protected void createHeadline(int position, LinearLayout ll) {
		IColorSchemeMapper csmi = Prefs.getInstance().getColorSchemeMapper();
		ll.setBackgroundDrawable(csmi.getResultContentInsideBackground());

		TextView tv = (TextView) ll.findViewById(R.id.headline);
		int sId;
		if (data.get(position).errors == 1)
			sId = R.string.autocomplete_found_mismatch;
		else
			sId = R.string.autocomplete_found_mismatches;

		String s = dv.getResources().getString(sId);
		tv.setText(MessageFormat.format(s, data.get(position).errors));
		tv.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
		tv.setTextColor(csmi.getResultContentInsideTextcolor());

	}

	protected void createContent(int position, LinearLayout ll) {
		IColorSchemeMapper csmi = Prefs.getInstance().getColorSchemeMapper();

		LeftRightValuesRecord lrvr = ((DictionaryRecordContent) getItem(position))
				.getLrvr();
		int maxSubRow;
		int crrSubRow;
		int foundIndex = Math.min(lrvr.getLeftRank().index,
				lrvr.getRightRank().index);
		// Log.d( TAG, "createContent: foundIndex = " + foundIndex );
		if (foundIndex < 3) {
			crrSubRow = 0;
			maxSubRow = Math.min(lrvr.getLeftValuesSize(),
					lrvr.getRightValuesSize());
		} else {
			// Log.d(TAG, "createContent: foundIndex = " + foundIndex +
			// " Line: "
			// + lrvr.getAllValues());
			crrSubRow = foundIndex;
			maxSubRow = foundIndex + 1;
		}
		// Log.d(TAG, "IndexedDictionaryAdapter: maxSubRow=" + maxSubRow
		// + " startSubRow = " + crrSubRow + ".");
		int crrChild = 0;
		while (crrSubRow < maxSubRow) {
			RelativeLayout crrLayout;
			if (crrChild < ll.getChildCount())
				crrLayout = (RelativeLayout) ll.getChildAt(crrChild);
			else {
				// Log.d(TAG,
				// "DictionaryAadpter: creating new child at position "
				// + crrChild + ".");
				crrLayout = (RelativeLayout) LayoutInflater.from(
						dv.getContext()).inflate(R.layout.dictionaryitemrow,
						ll, false);
				ll.addView(crrLayout);
			}
			TextView searchItemLeft = (TextView) crrLayout
					.findViewById(R.id.itemleft);
			TextView searchItemRight = (TextView) crrLayout
					.findViewById(R.id.itemright);

			if (d.getLanguage() == ContentAccess.LANGUAGE_LEFT
					|| d.getLanguage() == ContentAccess.LANGUAGE_BOTH) {
				searchItemLeft.setText(lrvr.getLeftNthValue(crrSubRow));
				searchItemRight.setText(lrvr.getRightNthValue(crrSubRow));
			} else if (d.getLanguage() == ContentAccess.LANGUAGE_RIGHT) {
				searchItemLeft.setText(lrvr.getRightNthValue(crrSubRow));
				searchItemRight.setText(lrvr.getLeftNthValue(crrSubRow));
			}

			searchItemLeft.setTextSize(16);
			searchItemRight.setTextSize(16);
			if (position % 2 == 0) {
				searchItemLeft
						.setTextColor(csmi.getResultContentTextcolorOne());
				searchItemRight.setTextColor(csmi
						.getResultContentTextcolorOne());
				if (crrChild > 0) {
					TextView dotLeft = (TextView) crrLayout
							.findViewById(R.id.dotleft);
					dotLeft.setText("●");
					dotLeft.setTextColor(csmi.getResultContentTextcolorOne());
					TextView dotRight = (TextView) crrLayout
							.findViewById(R.id.dotright);
					dotRight.setText("●");
					dotRight.setTextColor(csmi.getResultContentTextcolorOne());
				}
			} else {
				searchItemLeft
						.setTextColor(csmi.getResultContentTextcolorTwo());
				searchItemRight.setTextColor(csmi
						.getResultContentTextcolorTwo());
				if (crrChild > 0) {
					TextView dotLeft = (TextView) crrLayout
							.findViewById(R.id.dotleft);
					dotLeft.setText("●");
					dotLeft.setTextColor(csmi.getResultContentTextcolorTwo());
					TextView dotRight = (TextView) crrLayout
							.findViewById(R.id.dotright);
					dotRight.setText("●");
					dotRight.setTextColor(csmi.getResultContentTextcolorTwo());
				}
			}

			crrSubRow++;
			crrChild++;
		}
		int crrRemoveChild = ll.getChildCount() - 1;
		int firstEmptyChild = crrChild;
		while (crrRemoveChild >= firstEmptyChild) {
			ll.removeViewAt(crrRemoveChild);
			crrRemoveChild--;
		}

		if (position % 2 == 0) {
			ll.setBackgroundDrawable(csmi.getResultContentBackgroundOne());

		} else {
			ll.setBackgroundDrawable(csmi.getResultContentBackgroundTwo());

		}
	}

	private boolean isPositionOfProgressElement(int position) {
		return isLoadingData && position == data.size();
	}

	public SortedList<DictionaryRecord> getData() {
		return data;
	}

	public void addItem(DictionaryRecord item, boolean redrawList) {
		// Log.d(TAG, "addItem: errors = " + item.errors + " Line: "
		// + item.getLrvr().getAllValues());

		if (item.errors > lastMaxError) {
			// Log.d(TAG, "addItem: adding DictionaryRecordHeadline");
			DictionaryRecordHeadline dr = new DictionaryRecordHeadline(
					item.errors);
			data.addElement(dr);
			lastMaxError = item.errors;
		}
		data.addElement(item);
		if (redrawList) {
			notifyDataSetChanged();
		}
	}

	public void clear() {
		data.clear();
		lastMaxError = 0;
		notifyDataSetInvalidated();
	}

	public void remove(int position) {
		data.remove(position);
		notifyDataSetChanged();
	}
}
